<?php
namespace app\index\controller;

use app\common\controller\IndexBase;
use app\common\model\UserModel;
use app\common\service\LoginService;
use lib\SmsAli;
use think\captcha\facade\Captcha;
use think\exception\ValidateException;

class Login extends IndexBase
{

    /**
     * 账号密码登录
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            if( !$username || !$password ) {
                retError('账号或密码不能为空');
            }
            $show_captcha = xn_cfg('login.show_captcha');
            if( $show_captcha == '1' ) {
                if (!Captcha::check($this->request->post('captcha'))) {
                    retError('验证码不正确');
                }
            }
            try {
                $loginService = new LoginService();
                list($user, $token) = $loginService->login($username, $password);
                retSuccess(compact('user','token'),'登录成功');
            } catch (ValidateException $e) {
                retError($e->getError());
            }
        }

        return view();
    }

    /**
     * 注册
     */
    public function register()
    {
        if ($this->request->isPost()) {
            $account_type = xn_cfg('login.account_type', 'username');
            if( $account_type == 'mobile' ) {
                //是否需要短信验证码
                if( xn_cfg('login.ver_mobile') == '1' ) {
                    $sms = new SmsAli();
                    if( !$sms->checkCode($this->request->post('mobile'), $this->request->post('code')) ) {
                        retError('短信验证码不正确或已失效!');
                    }
                }
                $username = $this->request->post('mobile');
            }elseif ( $account_type == 'email') {
                //是否需要邮箱验证
                //todo

                $email = $this->request->post('email');
                if( !$email || !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
                    retError('邮箱格式不正确');
                }
                $username = $email;
            } else {
                $username = $this->request->post('username');
            }

            //图形验证码
            if (!Captcha::check($this->request->post('captcha'))) {
                retError('验证码不正确');
            }

            $data = [
                'mobile' => $this->request->post('mobile'),
                'email' => $this->request->post('email'),
                'username' => $username,
                'password' => $this->request->post('password'),
                'repassword' => $this->request->post('repassword'),
                'salt' => substr(md5(uniqid(true)), 0, 6),
                'nickname' => $this->request->post('nickname')??$username,
                'avatar' => $this->request->post('avatar'),
                'sex' => $this->request->post('sex'),
            ];
            try {
                validate(\app\common\validate\Login::class)
                    ->scene('register')
                    ->check($data);
                $loginService = new LoginService();
                list($user, $token) = $loginService->register($data);

            } catch (ValidateException $e) {
                retError($e->getError());
            }

            //删除短信验证码
            if( $account_type == 'mobile' && xn_cfg('login.ver_mobile') == '1' ) {
                $sms->deleteCode($this->request->post('mobile'));
            }
            retSuccess(compact('user'),'注册成功');
        }
        return view('');
    }

    /**
     * 验证码登录/注册
     * @return void
     */
    public function yzmLogin()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');

        if (!preg_match('/^1[3456789]\d{9}$/', $mobile)) {
            retError('手机号码不正确');
        }
        if (!$code) {
            retError('短信验证码不能为空');
        }

        $loginService = new LoginService();
        $sms = new SmsAli();
        if( !$sms->checkCode($mobile, $code) ) {
            $this->error('短信验证码不正确或已失效!');
        }
        list($user, $token) = $loginService->yzmLogin($mobile);

        $sms->deleteCode($mobile);
        retSuccess(compact('user'));
    }

    /**
     * 忘记密码
     */
    public function forget()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile');
            $code = $this->request->post('code');
            $password = $this->request->post('password');
            $repassword = $this->request->post('repassword');

            $sms = new SmsAli();
            if( !$sms->checkCode($mobile, $code) ) {
                retError('短信验证码不正确或已失效!');
            }

            $user = UserModel::where('mobile', $mobile)->find();
            if (!$user) {
                retError('手机号码未注册');
            }
            $data = [
                'mobile' => $mobile,
                'password' => $password,
                'repassword' => $repassword,
            ];
            try {
                validate(\app\common\validate\Login::class)
                    ->scene('forget')
                    ->check($data);
                $user->password = xn_encrypt($password, $user->salt);
                $user->save();
            } catch (ValidateException $e) {
                retError($e->getError());
            }

            //删除短信验证码
            $sms->deleteCode($mobile);
            retSuccess([],'密码重置成功');
        }

        return view('');
    }

    /**
     * 发送注册短信验证码
     * @return void
     */
    public function smsRegCode()
    {
        $mobile = $this->request->param('mobile');
        if (!preg_match('/^1[3456789]\d{9}$/', $mobile)) {
            retError('手机号码不正确');
        }

        //手机号是否已注册
        if ( UserModel::where('mobile', $mobile)->find() ) {
            retError('手机号码已注册');
        }

        $code = rand(100000,999999);
        $templateCode = xn_cfg('sms.ali_templateCode');
        $sms = new SmsAli();
        $templateParam = [
            'code' => $code
        ];
        $result = $sms->send($mobile, $templateParam, $templateCode, $msg);
        if( $result ) {
            //设置验证码有效时间 单位秒
            $expire_time = intval(xn_cfg('sms.valid_time'));
            $sms->setCode($mobile, $code, $expire_time);

            //设置可发间隔 单位秒
            $interval_time= intval(xn_cfg('sms.interval_time'));
            $sms->setIntervalTime($mobile, $interval_time);

            $this->success('短信已经发送，有效时间'.intdiv($expire_time, 60).'分钟');
        } else {
            $this->error($msg);
        }
    }

    /**
     * 忘记密码发送短信验证码
     */
    public function smsForgetCode()
    {
        $mobile = $this->request->param('mobile');
        if (!preg_match('/^1[3456789]\d{9}$/', $mobile)) {
            retError('手机号码不正确');
        }

        //手机号是否已注册
        if ( !UserModel::where('mobile', $mobile)->find() ) {
            retError('手机号码未注册');
        }

        $code = rand(100000,999999);
        $templateCode = xn_cfg('sms.ali_templateCode');
        $sms = new SmsAli();
        $templateParam = [
            'code' => $code
        ];
        $result = $sms->send($mobile, $templateParam, $templateCode, $msg);
        if( $result ) {
            //设置验证码有效时间 单位秒
            $expire_time = intval(xn_cfg('sms.valid_time'));
            $sms->setCode($mobile, $code, $expire_time);

            //设置可发间隔 单位秒
            $interval_time= intval(xn_cfg('sms.interval_time'));
            $sms->setIntervalTime($mobile, $interval_time);

            $this->success('短信已经发送，有效时间'.intdiv($expire_time, 60).'分钟');
        } else {
            $this->error($msg);
        }
    }

    /**
     * 生成图形验证码
     * @return \think\Response
     */
    public function captcha()
    {
        return Captcha::create();
    }
}